<script setup>
import { ref, onMounted } from 'vue'
import { useAuthStore } from '../../store/auth'
import { updateDoctor } from '../../api/doctor'
import { listDepartments, listPositions } from '../../api/admin'
import { ElMessage } from 'element-plus'

const auth = useAuthStore()
const form = ref({ doctorId: auth.currentId, name: '', phone: '', departmentId: '', positionId: '' })
const loading = ref(false)
const optionsLoading = ref(false)
const deptOptions = ref([])
const posOptions = ref([])

const fetchOptions = async () => {
  optionsLoading.value = true
  try {
    const [dpt, pos] = await Promise.all([
      listDepartments({ page: 1, size: 200 }).catch(() => ({ list: [] })),
      listPositions({ page: 1, size: 200 }).catch(() => ({ list: [] }))
    ])
    deptOptions.value = (dpt.list || []).map(it => ({ label: it.departmentName, value: it.departmentId }))
    posOptions.value = (pos.list || []).map(it => ({ label: it.positionName, value: it.positionId }))
  } finally { optionsLoading.value = false }
}

const prefill = () => {
  const u = auth.user || {}
  form.value = {
    doctorId: auth.currentId,
    name: u.name || '',
    phone: u.phone || '',
    departmentId: u.departmentId || '',
    positionId: u.positionId || ''
  }
}

const submit = async () => {
  loading.value = true
  try {
    const payload = {
      name: form.value.name,
      phone: form.value.phone,
      departmentId: form.value.departmentId || undefined,
      positionId: form.value.positionId || undefined,
    }
    await updateDoctor(auth.currentId, payload)
    ElMessage.success('更新成功')
  } finally { loading.value = false }
}

onMounted(async () => { prefill(); await fetchOptions() })
</script>

<template>
  <el-card>
    <h3>个人资料</h3>
    <el-form :model="form" label-width="120px" style="max-width:600px">
      <el-form-item label="姓名"><el-input v-model="form.name" placeholder="请输入姓名" /></el-form-item>
      <el-form-item label="手机号"><el-input v-model="form.phone" placeholder="11位手机号" /></el-form-item>
      <el-form-item label="科室">
        <el-select v-model="form.departmentId" placeholder="选择科室" :loading="optionsLoading" style="width: 260px" clearable>
          <el-option v-for="d in deptOptions" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="职称">
        <el-select v-model="form.positionId" placeholder="选择职称" :loading="optionsLoading" style="width: 260px" clearable>
          <el-option v-for="p in posOptions" :key="p.value" :label="p.label" :value="p.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>